package com.kerong.chedeli.view.home;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.google.gson.Gson;
import com.kerong.chedeli.CheDeLiApplication;
import com.kerong.chedeli.R;
import com.kerong.chedeli.data.modal.ShopListResult;
import com.kerong.chedeli.data.modal.ShopModal;
import com.kerong.chedeli.utils.AppManager;
import com.kerong.chedeli.utils.PreferencesUtils;
import com.kerong.chedeli.view.BaseActivity;
import com.kerong.chedeli.view.UIHelper;
import com.kerong.chedeli.view.tenant.OrderListActivity;
import com.kerong.chedeli.view.user.LoginActivity;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Logger;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import me.drakeet.materialdialog.MaterialDialog;

/**
 * Created by lyh on 15/10/16.
 */
public class MainNewActivity extends BaseActivity {

    @Bind(R.id.map)
    MapView mapView;
    BaiduMap baiduMap;
    @Bind(R.id.toolbar)
    Toolbar toolbar;

    public LocationClient mLocationClient = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_new);
        ButterKnife.bind(this);
        toolbar.setLogo(R.mipmap.ic_logo_banner);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        EventBus.getDefault().register(this);
        init();
        initLogin();
    }

    private void initLogin(){
        Intent intent = new Intent("com.kerong.chedeli.autologin");
        intent.setPackage(getPackageName());
        startService(intent);
    }

    private void init(){
        baiduMap = mapView.getMap();
        baiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        //设置标记点击事件
        baiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                if(null == marker.getExtraInfo())return true;
                LatLng latLng = marker.getPosition();
                View pop_view = getLayoutInflater().inflate(R.layout.view_map_pop, null);
                final ShopModal shopModal = marker.getExtraInfo().getParcelable("shop");
                TextView net_name = (TextView) pop_view.findViewById(R.id.net_name);
                TextView net_phone = (TextView) pop_view.findViewById(R.id.net_phone);
                TextView net_address = (TextView) pop_view.findViewById(R.id.net_address);
                net_name.setText("网点名称："+shopModal.getShop_name());
                net_phone.setText("网点电话："+shopModal.getShop_phone());
                net_address.setText("网点地址:" + shopModal.getAddress());
                InfoWindow infoWindow = new InfoWindow(pop_view,marker.getPosition(),-65);
                baiduMap.showInfoWindow(infoWindow);
                pop_view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        baiduMap.hideInfoWindow();
                        Intent intent = new Intent();
                        intent.putExtra("shop",shopModal);
                        turnToActivity(CarListActivity.class,intent);
                    }
                });
                return true;
            }
        });
        mLocationClient = new LocationClient(getApplicationContext());
        initLocation();
        mLocationClient.registerLocationListener(new BDLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation bdLocation) {
                CheDeLiApplication.location = bdLocation;
                com.orhanobut.logger.Logger.i("开始定位--定位成功:lon:" + bdLocation.getLongitude()
                        + " lat:  " + bdLocation.getLatitude());
                baiduMap.setMyLocationEnabled(true);
                LatLng latLng = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());
                MapStatus mapStatus = new MapStatus.Builder()
                        .target(latLng)
                        .zoom(18)
                        .build();
                MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mapStatus);
                baiduMap.setMapStatus(mapStatusUpdate);
                initLocationMarket(bdLocation);
                initRemoteDataMarketData(bdLocation);
                mLocationClient.stop();
            }
        });
        mLocationClient.start();

    }

    private void initLocationMarket(BDLocation bdLocation){
        //定义Maker坐标点
        LatLng point = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());
        //构建Marker图标
        BitmapDescriptor bitmap = BitmapDescriptorFactory
                .fromResource(R.mipmap.ic_location);
        //构建MarkerOption，用于在地图上添加Marker
        OverlayOptions option = new MarkerOptions()
                .position(point)
                .icon(bitmap);
        //在地图上添加Marker，并显示
        baiduMap.addOverlay(option);
    }
    private void initReomateMarket(ShopModal shopModal){
        //定义Maker坐标点
        LatLng point = new LatLng(Double.parseDouble(shopModal.getLocation().getLat()),Double.parseDouble(shopModal.getLocation().getLng()));
        //构建Marker图标
        BitmapDescriptor bitmap = BitmapDescriptorFactory
                .fromResource(R.mipmap.ic_car_net);
        //构建MarkerOption，用于在地图上添加Marker
        OverlayOptions option = new MarkerOptions()
                .position(point)
                .icon(bitmap);
        //在地图上添加Marker，并显示
        Bundle bundle = new Bundle();
        bundle.putParcelable("shop", shopModal);
        baiduMap.addOverlay(option).setExtraInfo(bundle);
    }

    private void initRemoteDataMarketData(BDLocation bdLocation){
        FinalHttp finalHttp = new FinalHttp();
        String url = "http://cdlmapi.0371e.cn/v1/shopsearch";
        AjaxParams ajaxParams = new AjaxParams();
        ajaxParams.put("region", bdLocation.getCity());
        ajaxParams.put("nearby", "10000");
        ajaxParams.put("lat", bdLocation.getLatitude() + "");
        ajaxParams.put("lng", bdLocation.getLongitude() + "");
        finalHttp.get(url, ajaxParams, new AjaxCallBack<String>() {
            @Override
            public void onSuccess(String s) {
                try {
                    ShopListResult shopListResult = new Gson().fromJson(s, ShopListResult.class);
                    List<ShopModal> modalList = shopListResult.getResults();
                    com.orhanobut.logger.Logger.i("shoplist：%s", modalList.size() + "");

                    if (null != modalList) {
                        for (ShopModal shopModal : modalList) {
                            initReomateMarket(shopModal);
                        }
                    }
                } catch (Exception e) {
                    UIHelper.showMessage("网点数据解析失败请联系管理员");
                }

            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                UIHelper.showMessage("网点数据加载失败，请联系管理员");
            }
        });
    }
    private void initLocation(){
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy
        );//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系
        int span=1000;
        option.setScanSpan(span);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
        option.setOpenGps(true);//可选，默认false,设置是否使用gps
        option.setLocationNotify(true);//可选，默认false，设置是否当gps有效时按照1S1次频率输出GPS结果
        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
        option.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
        option.setIgnoreKillProcess(false);//可选，默认false，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认杀死
        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤gps仿真结果，默认需要
        mLocationClient.setLocOption(option);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if(keyCode == KeyEvent.KEYCODE_BACK ){
            exit();//双击退出
        }
        return false;

    }
    boolean isExit = false;
    private void exit(){
        Timer timer = null;
        if(!isExit){
            isExit  = true;
            Toast.makeText(this, R.string.exit_text, Toast.LENGTH_SHORT).show();
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    isExit = false;
                }
            },2000);
        }else{
            AppManager.getAppManager().AppExit(this);
        }

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_order:
                com.orhanobut.logger.Logger.i("执行我的订单查询");
                if(!PreferencesUtils.getBoolean(this,CheDeLiApplication.PRE_LOGIN_STATUS,false)||
                        null == CheDeLiApplication.getUserMoal()){
                    UIHelper.showMessage("请先登陆");
                    turnToActivity(LoginActivity.class);
                }else{
                    turnToActivity(OrderListActivity.class);
                }
                break;
            case R.id.menu_login:
                if(!PreferencesUtils.getBoolean(this,CheDeLiApplication.PRE_LOGIN_STATUS,false)||
                        null == CheDeLiApplication.getUserMoal()){
                    turnToActivity(LoginActivity.class);
                }else{
                    //turnToActivity(OrderListActivity.class);
                      final MaterialDialog mMaterialDialog = new MaterialDialog(this);
                        mMaterialDialog.setTitle("退出确认")
                            .setMessage("确定退出该账号吗?")
                            .setPositiveButton("确定", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    PreferencesUtils.putBoolean(MainNewActivity.this,CheDeLiApplication.PRE_LOGIN_STATUS,false);
                                    invalidateOptionsMenu();
                                  mMaterialDialog.dismiss();
                                }
                            })
                            .setNegativeButton("取消", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    mMaterialDialog.dismiss();
                                }
                            });

                    mMaterialDialog.show();
                }
                break;

        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.menu_new_main, menu);
        MenuItem menuItem = menu.findItem(R.id.menu_login);
        if(PreferencesUtils.getBoolean(this,CheDeLiApplication.PRE_LOGIN_STATUS,false)){

            menuItem.setIcon(R.mipmap.ic_ren_login);
        }else{
            menuItem.setIcon(R.mipmap.ic_ren_exit);
        }
        return true;
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        MenuItem menuItem = menu.findItem(R.id.menu_login);
        if(PreferencesUtils.getBoolean(this,CheDeLiApplication.PRE_LOGIN_STATUS,false)){
            menuItem.setIcon(R.mipmap.ic_ren_login);
        }else{
            menuItem.setIcon(R.mipmap.ic_ren_exit);
        }
        return super.onPrepareOptionsMenu(menu);
    }

    public void onEvent(String event){
        if(event == "loginsuccess"){
            invalidateOptionsMenu();
        }
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}
